<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    function formatNum(num){
      return num && num.toString().replace(/(?=(?!^)(\d{3})+$)/g, ',')
    }

    `
      (?= (?!^) (\d{3} ) + $)

    `
    let num = 1000000

    let res = formatNum(num);
    console.log(res);

  </script>
</body>
</html>